package com.android.settings.ios.general;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;

import androidx.preference.Preference;

import com.android.settings.ios.BaseFragment;
import com.android.settings.ios.R;
import com.android.settings.ios.view.OsPreference;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class GeneralFragment extends BaseFragment {

    private OsPreference mWarrantyPref;

    public GeneralFragment() {

    }

    public GeneralFragment(String title) {
        Bundle bundle = new Bundle();
        bundle.putString("fragment_title", title);
        setArguments(bundle);
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.general_main_fragment);

        mWarrantyPref = findPreference("menu_warranty");

        ContentResolver cr = getActivity().getContentResolver();
        Calendar calendar = Calendar.getInstance();
        int year = Settings.Global.getInt(cr, "key_limited_year", calendar.get(Calendar.YEAR) + 1);
        int month = Settings.Global.getInt(cr, "key_limited_month", calendar.get(Calendar.MONTH));
        int day = Settings.Global.getInt(cr, "key_limited_day", calendar.get(Calendar.DAY_OF_MONTH));
        calendar.set(year, month, day);
        String limited = getResources().getString(R.string.limited_summary);
        limited += new SimpleDateFormat("yyyy/M/d", Locale.getDefault()).format(calendar.getTimeInMillis());
        mWarrantyPref.setSummary(limited);
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        final String key = preference.getKey();
        Intent intent = new Intent();
        if ("menu_shutdown".equals(key)) {
            intent.setPackage("com.android.sec.poweroff");
            intent.setClassName("com.android.sec.poweroff", "com.android.sec.poweroff.PoService");
            getActivity().startService(intent);
            return true;
        } else if ("menu_fota".equals(key)) {
            intent = new Intent();
            intent.setComponent(new ComponentName("com.adups.fota", "com.adups.fota.GoogleOtaClient"));
            getActivity().startActivity(intent);
            return true;
        } else if ("menu_warranty".equals(key)) {
            intent = new Intent(Intent.ACTION_MAIN);
            intent.putExtra("last_title", getString(R.string.general));
            intent.setComponent(new ComponentName("com.android.screentime", "com.android.settings.LimitedWarrantyActivity"));
            getActivity().startActivity(intent);
            return true;
        }
        return super.onPreferenceTreeClick(preference);
    }
}
